package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.UploadFileRequestDto;
import com.molichuxing.framework.dto.UploadFileResponseDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.framework.utils.UploadUtil;
import com.molichuxing.gateway.api.config.OptionalLogConfig;
import com.molichuxing.gateway.api.services.BasicApiService;
import com.molichuxing.gateway.bff.advert.entity.response.MessageVo;
import com.molichuxing.gateway.bff.advert.entity.response.RiskEmailVo;
import com.molichuxing.gateway.bff.basic.entity.request.modify.RiskEmailModifyVo;
import com.molichuxing.gateway.bff.basic.entity.response.*;
import com.molichuxing.gateway.bff.basic.services.*;
import com.molichuxing.gateway.bff.car.entity.response.MaintenanceConfigVo;
import com.molichuxing.gateway.bff.car.entity.response.RegionSubcompanyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/basic")
@Api(tags = "基础数据")
public class BasicApiServiceImpl extends RootApiService implements BasicApiService {
    private static final Logger logger = LoggerFactory.getLogger(BasicApiServiceImpl.class);

    @Resource
    private BasicBffService baiscBffService;

    @Resource
    private FileStorageBffService fileStorageBffService;

    @Resource
    private VehicleBffService vehicleBffService;

    @Resource
    private ReceiptCompanyBffService receiptCompanyBffService;

    @Resource
    private DictBffService dictBffService;

    @Override
    @ApiOperation(value = "获取保险公司关系")
    @GetMapping(value = "/insurance/company")
    public ResponseResult<List<InsuranceCompanyVo>> getInsuranceCompany() {
        ResponseResult<List<InsuranceCompanyVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getInsurance());
        } catch (Exception e) {
            logger.error("[getInsuranceCompany]获取保险公司关系信息异常", e);
            result.error("获取保险公司关系信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取省市区父子级关系")
    @ApiImplicitParams({@ApiImplicitParam(name = "level", value = "等级，不传表示所有，1：省，2：市，3：区", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "type", value = "类别（dealer：经销商,store:门店）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "dealerId", value = "经销商id", required = false, dataType = "String")
    })
    @GetMapping(value = "/region/getallcity")
    public ResponseResult<List<RegionCityVo>> getAllCity(@RequestParam Map<String, Object> selectParams) {
        ResponseResult<List<RegionCityVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getAllCity(selectParams));
        } catch (Exception e) {
            logger.error("[getAllCity]获取省市区父子级别信息异常", e);
            result.error("获取省市区父子级别信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取分子公司列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "公司简称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "responsibleAccountName", value = "负责人姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "regionId", value = "城市", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")

    })
    @GetMapping(value = "/subcompany/list")
    public ResponseResult<Paged<SubcompanyVo>> getSubcompanyList(@RequestParam Map<String, Object> selectParams) {
        ResponseResult<Paged<SubcompanyVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getSubcompanyListPage(selectParams));
        } catch (Exception e) {
            logger.error("[getSubcompanyList]获取分子公司列表异常", e);
            result.error("获取分子公司列表异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "根据分子公司id 获取分子公司详情")
    @ApiImplicitParam(name = "id", value = "分子公司id", required = true, dataType = "Integer")
    @GetMapping(value = "/subcompany/getsubcompany")
    public ResponseResult<SubcompanyVo> getSubcompanyVo(@RequestParam Integer id) {
        ResponseResult<SubcompanyVo> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getSubcompany(id));
        } catch (Exception e) {
            logger.error("[getsubcompany]根据分子公司id 获取分子公司详情异常", e);
            result.error("根据分子公司id 获取分子公司详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "新增分子公司")
    @PostMapping(value = "/subcompany/create")
    @OptionalLogConfig(methods = "新增分子公司")
    public ResponseResult<Boolean> createSubcompany(@RequestBody @Valid SubcompanyVo subcompanyVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.createSubcompany(subcompanyVo));
        } catch (BizException e) {
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[createSubcompany]新增分子公司异常", e);
            result.error("新增分子公司异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "修改分子公司")
    @PostMapping(value = "/subcompany/modify")
    @OptionalLogConfig(methods = "修改分子公司")
    public ResponseResult<Boolean> modifySubcompany(@RequestBody @Valid SubcompanyVo subcompanyVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.modifySubcompany(subcompanyVo));
        } catch (BizException e) {
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[modifySubcompany]修改分子公司异常", e);
            result.error("修改分子公司异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取产权方列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")})
    @GetMapping(value = "/ownership/list")
    public ResponseResult<Paged<OwnershipVo>> getOwnershipListPage(@RequestParam Map<String, Object> selectParams) {
        ResponseResult<Paged<OwnershipVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getOwnershipListPage(selectParams));
        } catch (Exception e) {
            logger.error("[getOwnershipListPage]获取产权方列表异常", e);
            result.error("获取产权方列表异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "新增产权方")
    @PostMapping(value = "/ownership/create")
    @OptionalLogConfig(methods = "新增产权方")
    public ResponseResult<Boolean> createOwnership(@RequestBody @Valid OwnershipVo ownershipVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.createOwnership(ownershipVo));
        } catch (BizException e) {
            logger.error("[createOwnership]新增产权方异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[createOwnership]新增产权方异常", e);
            result.error("新增产权方异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "修改产权方")
    @PostMapping(value = "/ownership/modify")
    @OptionalLogConfig(methods = "修改产权方")
    public ResponseResult<Boolean> modifyOwnership(@RequestBody @Valid OwnershipVo ownershipVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.modifyOwnership(ownershipVo));
        } catch (BizException e) {
            logger.error("[modifyOwnership]修改产权方异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyOwnership]修改产权方异常", e);
            result.error("修改产权方异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "根据id查询产权方详情")
    @ApiImplicitParam(name = "ownershipId", value = "产权方id", required = true, dataType = "Integer")
    @GetMapping(value = "/ownership/id")
    public ResponseResult<OwnershipDetailVo> getOwnershipById(@RequestParam Integer ownershipId) {
        ResponseResult<OwnershipDetailVo> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getOwnershipById(ownershipId));
        } catch (Exception e) {
            logger.error("[getsubcompany]根据id查询产权方详情异常", e);
            result.error("根据id查询产权方详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "根据省份id查询分子公司列表")
    @ApiImplicitParam(name = "provinceId", value = "省份id", required = false, dataType = "Integer")
    @GetMapping(value = "/ownership/provinceId")
    public ResponseResult<List<SubcompanyVo>> getOwnershipByProvinceId(@RequestParam(required = false) Integer provinceId) {
        ResponseResult<List<SubcompanyVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getOwnershipByProvinceId(provinceId));
        } catch (Exception e) {
            logger.error("[getsubcompany]根据id查询产权方详情异常", e);
            result.error("根据id查询产权方详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询子品牌车系车型信息")
    @GetMapping(value = "/vehicle/make")
    public ResponseResult<List<VehicleModlemakeVo>> getVehicleModlemake() {
        ResponseResult<List<VehicleModlemakeVo>> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.getVehicleModlemakeBizDto());
        } catch (Exception e) {
            logger.error("[getVehicleModlemake]查询子品牌车系车型信息异常", e);
            result.error("查询子品牌车系车型信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询子品牌车系车型信息-保养")
    @GetMapping(value = "/vehicle/make/maintenance")
    public ResponseResult<List<VehicleModlemakeVo>> getMaintenanceVehicleModlemake() {
        ResponseResult<List<VehicleModlemakeVo>> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.getMaintenanceVehicleModlemakeBizDto());
        } catch (Exception e) {
            logger.error("[getVehicleModlemake]查询子品牌车系车型信息异常", e);
            result.error("查询子品牌车系车型信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询所有收款方信息")
    @GetMapping(value = "/receipt/company")
    public ResponseResult<List<ReceiptCompanyVo>> receiptCompany() {
        ResponseResult<List<ReceiptCompanyVo>> result = new ResponseResult<>();
        try {
            result.success(receiptCompanyBffService.getReceiptCompany());
        } catch (BizException e) {
            logger.error("[receiptCompany]获取所有收款方信息异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[receiptCompany]获取所有收款方信息异常", e);
            result.error("文获取所有收款方信息失败");
        }

        return result;
    }

    @Override
    @ApiOperation(value = "获取车辆品牌列表")
    @ApiImplicitParam(name = "isMainMake", value = "是否是主品牌（ 0:否，1是）", required = true, dataType = "Integer")
    @GetMapping(value = "/vehicle/make/list")
    public ResponseResult<List<VehicleMakeVo>> getModelMakeList(@RequestParam Integer isMainMake) {
        ResponseResult<List<VehicleMakeVo>> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.getModelMakeList(isMainMake));
        } catch (Exception e) {
            logger.error("[getsubcompany]根据id查询产权方详情异常", e);
            result.error("根据id查询产权方详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "文件上传-单个")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "文件类型（user：用户，dealer：经销商，vehicle：车辆，"
                    + "advertising：广告，accident：事故，maintenance：保养，check：车辆检验，contract：合同，invoice：发票，"
                    + "finance：财务）", required = true, dataType = "String")})
    @PostMapping(value = "/upload/{type}")
    public ResponseResult<UploadFileResponseDto> uploadFile(HttpServletRequest request, MultipartFile file,
                                                            @PathVariable("type") String type) {
        ResponseResult<UploadFileResponseDto> result = new ResponseResult<>();
        try {
            // 查询文件存储配置
            UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig(type);
            if (uploadFileRequestDto == null) {
                result.error(ResponseCodeEnum.UPLOAD_ERROR.getCode(), "文件上传失败,不存在的文件类型");
            }

            UploadFileResponseDto uploadFileResponseDto = UploadUtil.uploadFileToAll(file, uploadFileRequestDto);
            if (uploadFileResponseDto == null) {
                result.error(ResponseCodeEnum.ABNORMAL_ERROR.getCode(), "文件上传失败,文件为空");
            } else {
                result.success(uploadFileResponseDto);
            }
        } catch (BizException e) {
            logger.error("[uploadFile]文件上传异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[uploadFile]文件上传异常", e);
            result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "文件上传失败");
        }

        return result;
    }

    @Override
    @ApiOperation(value = "文件上传-批量")
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "文件类型（user：用户，dealer：经销商，vehicle：车辆，"
            + "advertising：广告，accident：事故，maintenance：保养，check：车辆检验，contract：合同，invoice：发票，"
            + "finance：财务）", required = true, dataType = "String")})
    @PostMapping(value = "/upload/{type}/batch")
    public ResponseResult<List<UploadFileResponseDto>> uploadFileBatch(HttpServletRequest request,
                                                                       MultipartFile[] files,
                                                                       @PathVariable("type") String type) {
        ResponseResult<List<UploadFileResponseDto>> result = new ResponseResult<>();
        try {
            // 查询文件存储配置
            UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig(type);
            if (uploadFileRequestDto == null) {
                result.error(ResponseCodeEnum.UPLOAD_ERROR.getCode(), "文件上传失败,不存在的文件类型");
            }
            if (files.length == 1) {
                result.success(Arrays.asList(UploadUtil.uploadFileToAll(files[0], uploadFileRequestDto)));
            } else {
                result.success(UploadUtil.uploadFileBatchToAll(files, uploadFileRequestDto));
            }
            result.success(UploadUtil.uploadFileBatchToAll(files, uploadFileRequestDto));
        } catch (BizException e) {
            logger.error("[uploadFileBatch]文件批量上传异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[uploadFileBatch]文件批量上传异常", e);
            result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "文件批量上传失败");
        }

        return result;
    }

    @Override
    @ApiOperation(value = "查询省下有分子公司的列表信息")
    @GetMapping(value = "/province/sub/company")
    public ResponseResult<List<RegionSubcompanyVo>> getProvinceSubCompany() {
        ResponseResult<List<RegionSubcompanyVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getProvinceSubCompany());
        } catch (Exception e) {
            logger.error("[province/sub/company]查询省下有分子公司的信息异常", e);
            result.error("查询省下有分子公司的信息异常");
        }
        return result;
    }


    @Override
    @ApiOperation(value = "根据车型id获取车型全称")
    @ApiImplicitParam(name = "vehicleId", value = "车型id", required = true, dataType = "Integer")
    @GetMapping(value = "/vehicle/full/name")
    public ResponseResult<String> getVehicleName(@RequestParam Integer vehicleId) {
        ResponseResult<String> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.getVehicleName(vehicleId));
        } catch (Exception e) {
            logger.error("[getVehicleName]根据车型id获取车型全称异常", e);
        }
        return result;
    }

    @Override
    @ApiOperation(value = "根据类型获取采购车辆基础信息")
    @ApiImplicitParam(name = "type", value = "类型：1：租期，2：付款周期", required = false, dataType = "Integer")
    @GetMapping(value = "/vehicle/purchase/param")
    public ResponseResult<List<PurchaseParamDicVo>> getPurchaseDict(@RequestParam(required = false) Integer type) {
        ResponseResult<List<PurchaseParamDicVo>> result = new ResponseResult<>();
        try {
            return result.success(dictBffService.getPurchaseDict(type));
        } catch (Exception e) {
            logger.error("[getPurchaseDict]根据类型获取采购车辆基础信息", e);
        }
        return result;
    }


    @Override
    @ApiOperation(value = "获取车型管理列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/vehicle/list")
    public ResponseResult<Paged<VehicleModleMakeInfoVo>> getVehiclePage(@RequestParam Map<String, Object> map,
                                                                        @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<VehicleModleMakeInfoVo>> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.getVehiclePage(map, pageNum, pageSize));
        } catch (BizException e) {
            logger.error("[getVehiclePage]获取车型管理列表信息异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getVehiclePage]获取车型管理列表信息异常", e);
            result.error("获取车型管理列表信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取车型详情")
    @ApiImplicitParam(name = "modelId", value = "车型id", required = true, dataType = "Integer")
    @GetMapping(value = "/vehicle/detail")
    public ResponseResult<VehicleModleMakeInfoVo> getVehicleInfo(@RequestParam Integer modelId) {
        ResponseResult<VehicleModleMakeInfoVo> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.getVehicleInfo(modelId));
        } catch (BizException e) {
            logger.error("[getVehicleInfo]获取车型详情异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getVehicleInfo]获取车型详情异常", e);
            result.error("获取车型详情异常");
        }
        return result;
    }
    
    
    @Override
    @ApiOperation(value = "消息提醒列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")

    })
    @GetMapping(value = "/message/list")
    public ResponseResult<Paged<MessageVo>> getMessageListPage(@RequestParam Map<String, Object> map) {
        ResponseResult<Paged<MessageVo>> result = new ResponseResult<>();
        try {
        	Integer pageNum = ObjectCastUtil.castInteger(map.get("pageNum"));
			if(null==pageNum || pageNum < 1 ) {
				map.put("pageNum",1);
			}
			Integer pageSize = ObjectCastUtil.castInteger(map.get("pageSize"));
			if(null==pageSize || pageSize <= 0) {
				map.put("pageSize", 10);
			}

            return result.success(baiscBffService.getMessageListPage(map));
        } catch (Exception e) {
            logger.error("[getMessageListPage]获取消息提醒列表异常", e);
            result.error("消息提醒列表异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "消息提醒详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "receiveType", value = "接收类型(1：邮件收件人，3：电话短信接收人)", required = true, dataType = "Integer")

    })
    @GetMapping(value = "/message/detail")
    public ResponseResult<List<RiskEmailVo>> getMessageDetails(@RequestParam Integer type,@RequestParam Integer receiveType) {
        ResponseResult<List<RiskEmailVo>> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.getlistRiskEmail(type, receiveType));
        } catch (Exception e) {
            logger.error("[getMessageDetails]获取消息提醒详情异常", e);
            result.error("消息提醒详情异常");
        }
        return result;
    }
    
    @Override
    @ApiOperation(value = "消息编辑")
    @PostMapping(value = "/message/modify")
    @OptionalLogConfig(methods = "消息编辑")
    public ResponseResult<Boolean> modifyRiskEmail(@RequestBody(required=false) List<RiskEmailModifyVo> list) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(baiscBffService.modifyRiskEmail(list));
        } catch (BizException e) {
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyRiskEmail]消息编辑异常", e);
            result.error("消息编辑异常");
        }
        return result;
    }
}
